<?php
namespace App\Library\System\Sub;

use App\Library\System\Model\AppModel;
use App\Library\System\App;
use App\Library\System\Model\UserModel;

class Auth extends App
{

    public $login, $model;

    public function __construct()
    {
        parent::__construct();
        $this->login = false;
        $id = $this->session('user_id');

        if ((!empty($id)) && ($id > 0)) {
            $this->login = true;
        }

        $this->app = AppModel::getInstance();
    }

    public function login($email, $hash_password, $remember)
    {

        if ($this->login) {
            return true; // You have already loginned
        }

        $encode_password = $this->process->encodePassword($email, $hash_password);

        $users = $this->app->loginUser($email, $encode_password);

        if ($users->count() == 1) // Unique
        {
            $user = new UserModel($users->current()->id);

            // Save user to Session
            $this->app->saveUser($user->id, $user->name);

            // Remember me in cookie for next login
            if ($remember) {
                $this->app->rememberUser($user->id, $user->getSignature());
            }

            $this->login = true;
        }

        return $this->login;
    }

    public function currentUser()
    {
        return $this->session('user_id');
    }

    public function getSecurityToken()
    {
        return 'abcdef';
    }

    public function checkSecurityToken()
    {

    }

    public function logout()
    {
        $this->login = false;
        $this->app->logoutUser();
    }
}